<template>
  <div class="transition_box">
    <div class="schedule_bar">
      <span class="L_label">发布时间：</span>
      <div class="date_picker">
        <div class="date_input" @click.stop="() => {}">
          <input
            type="text"
            placeholder="选择日期"
            :class="inputActive == 'dateInputActive' ? 'active' : ''"
            v-model="date"
            @click="openPanel('dateInputActive', 'datePanelActive')"
            @blur="checkTime({ date })"
          />
          <i
            class="calendar active"
            @click="openPanel('dateInputActive', 'datePanelActive')"
          ></i>
          <div class="date_panel" v-if="inputActive == 'dateInputActive'">
            <div class="ym">
              <div class="button" @click.stop="setMonth('-')">
                <span class="arrow left"></span>
              </div>
              <span>{{ year }}年 {{ month }}月</span>
              <div class="button" @click.stop="setMonth('+')">
                <span class="arrow right"></span>
              </div>
            </div>
            <div class="md">
              <div class="week">
                <span>日</span>
                <span>一</span>
                <span>二</span>
                <span>三</span>
                <span>四</span>
                <span>五</span>
                <span>六</span>
              </div>
              <div class="days">
                <div
                  class="day"
                  v-for="day in daysArr"
                  :class="[
                    year == selectYear &&
                    month == selectMonth &&
                    day == selectDay
                      ? 'active'
                      : '',
                    dayDisable(day) ? 'disable' : '',
                  ]"
                  @click="selectTime({ day })"
                >
                  {{ day }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="scroll_input" @click.stop="() => {}">
          <div
            class="s_input_wrap"
            @click="openPanel('hourInputActive', 'hourPanelActive')"
          >
            <input
              type="number"
              class="s_input"
              :class="inputActive == 'hourInputActive' ? 'active' : ''"
              v-model="selectHour"
            />
          </div>
          <span
            class="arrow_down"
            :class="inputActive == 'hourInputActive' ? 'active' : ''"
            @click="openPanel('hourInputActive', 'hourPanelActive')"
          ></span>
          <span class="s_label">时</span>
          <div class="s_panel" v-show="inputActive == 'hourInputActive'">
            <div
              class="s_item"
              v-for="h in 24"
              v-if="h > hour"
              :class="selectHour == h - 1 ? 'active' : ''"
              @click="selectTime({ h: h - 1 })"
            >
              {{ h - 1 }}
            </div>
          </div>
        </div>
        <div class="scroll_input" @click.stop="() => {}">
          <div
            class="s_input_wrap"
            @click="openPanel('mdInputActive', 'mdPanelActive')"
          >
            <input
              type="number"
              class="s_input"
              :class="inputActive == 'mdInputActive' ? 'active' : ''"
              v-model="selectMinute"
            />
          </div>
          <span
            class="arrow_down"
            :class="inputActive == 'mdInputActive' ? 'active' : ''"
            @click="openPanel('mdInputActive', 'mdPanelActive')"
          ></span>
          <span class="s_label">分</span>
          <div class="s_panel" v-show="inputActive == 'mdInputActive'">
            <div
              class="s_item"
              v-for="m in 60"
              v-if="m > minute"
              :class="selectMinute == m - 1 ? 'active' : ''"
              @click="selectTime({ m: m - 1 })"
            >
              {{ m - 1 }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputActive: "",
      panelActive: "",
      date: "",
      lastInputDate: "",
      year: 0,
      month: 0,
      day: 0,
      week: 0,
      hour: 0,
      minute: 0,
      currentYear: 0,
      currentMonth: 0,
      currentDay: 0,
      currentHour: 0,
      currentMinute: 0,
      selectYear: 0,
      selectMonth: 0,
      selectDay: 0,
      selectHour: 0,
      selectMinute: 0,
      docCB: null, //页面监听回调
    };
  },
  props: {
    maxRegularTime: {
      typeof: Number,
      required: false,
    },
  },
  mounted() {
    this.getNowDate();
    this.watchGetScheduleContent();
  },
  methods: {
    // 文档单次监听回调
    documentAddEventListen(type, cb) {
      this.docCB = () => {
        cb();
        document.documentElement.removeEventListener(type, this.docCB);
      };
      document.documentElement.addEventListener(type, this.docCB);
    },
    documentRemoveEventListen(type, cb) {
      if (cb) document.documentElement.removeEventListener(type, cb);
    },
    // 检查日期输入格式
    checkTime({ date = null, h = null, m = null } = {}) {
      let dateReg = new RegExp(/^\d{4}-\d{1,2}-\d{1,2}$/);
      let dateFlag = true;
      let dateArr = date.split("-");
      let year = Number(dateArr[0]);
      let month = Number(dateArr[1]);
      let day = Number(dateArr[2]);
      if (date) {
        if (dateReg.test(date)) {
          // 如果年比当前年小，则错误
          if (year < this.currentYear) {
            dateFlag = false;
          }
          // 如果年等于当前年，则判断月份
          else if (year == this.currentYear) {
            if (month < this.currentMonth || month > 12) {
              dateFlag = false;
            }
            // 如果不是当前月
            else if (month != this.currentMonth) {
              switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                  if (day > 31) dateFlag = false;
                  break;
                case 4:
                case 6:
                case 9:
                case 11:
                  if (day > 30) dateFlag = false;
                  break;
                default:
                  if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                    if (day > 29) dateFlag = false;
                  } else {
                    if (day > 28) dateFlag = false;
                  }
                  break;
              }
            } else {
              if (day < this.currentDay) {
                dateFlag = false;
              }
            }
          }
          // 如果年大于当前年，则判断月份
          else if (year > this.currentYear) {
            if (month < 0 || month > 12) {
              dateFlag = false;
            } else {
              switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                  if (day > 31) dateFlag = false;
                  break;
                case 4:
                case 6:
                case 9:
                case 11:
                  if (day > 30) dateFlag = false;
                  break;
                default:
                  if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                    if (day > 29) dateFlag = false;
                  } else {
                    if (day > 28) dateFlag = false;
                  }
                  break;
              }
            }
          }
        } else {
          dateFlag = false;
        }
      } else {
        dateFlag = false;
      }
      if (dateFlag) {
        this.date = `${year}-${month}-${day}`;
        this.lastInputDate = this.date;
      } else {
        this.date = this.lastInputDate;
        return false;
      }
      if (h == null || h < this.hour || h > 23) return false;
      if (m == null || m < this.minute || m > 59) return false;
      return true;
    },
    // 展开选框
    openPanel(inputActive, panelActive) {
      if (inputActive) {
        this.$set(this, "inputActive", inputActive);
      }
      if (panelActive) {
        this.$set(this, "panelActive", panelActive);
      }
      this.documentAddEventListen("click", this.closePanel);
    },
    // 关闭选框
    closePanel() {
      this.documentRemoveEventListen("click", this.docCB);
      this.$set(this, "inputActive", "");
      this.$set(this, "panelActive", "");
    },
    // 计算当前时间
    getNowDate() {
      let time = new Date();

      this.year = time.getFullYear();
      this.currentYear = this.year;
      this.selectYear = this.year;

      this.month = time.getMonth() + 1;
      this.currentMonth = this.month;
      this.selectMonth = this.month;

      this.day = time.getDate();
      this.currentDay = this.day;
      this.selectDay = this.day;

      this.hour = time.getHours();
      this.currentHour = this.hour;
      this.selectHour = this.hour;

      this.minute = time.getMinutes();
      this.currentMinute = this.minute;
      this.selectMinute = this.minute;
      this.setDate();
      this.lastInputDate = this.date;
    },
    // 增减月份
    setMonth(type) {
      if (type == "-") {
        this.month--;
        if (this.month < 1) {
          this.month = 12;
          this.year--;
        }
      } else if (type == "+") {
        this.month++;
        if (this.month > 12) {
          this.month = 1;
          this.year++;
        }
      }
    },
    // 设置日期
    setDate() {
      this.date = `${this.selectYear}-${this.selectMonth}-${this.selectDay}`;
    },
    // 选择时间
    selectTime({ day = null, h = null, m = null } = {}) {
      if (day && this.dayDisable(day)) return;
      if (typeof h == "number") {
        this.selectHour = h;
      }
      if (typeof m == "number") {
        this.selectMinute = m;
      }
      if (day) {
        this.selectYear = this.year;
        this.selectMonth = this.month;
        this.selectDay = day;
        // 计算时间区间
        let dateNum =
          new Date(`${this.year}-${this.month}-${day}`).getTime() / 1000; //当前选中的值对应秒
        let curDateNum =
          new Date(
            `${this.currentYear}-${this.currentMonth}-${this.currentDay}`
          ).getTime() / 1000; //当前日期对应秒
        if (dateNum > curDateNum) {
          this.hour = 0;
          this.minute = 0;
        } else {
          this.hour = this.currentHour;
          this.minute = this.currentMinute;
          if (this.selectHour < this.currentHour)
            this.selectHour = this.currentHour;
          if (this.selectMinute < this.currentMinute)
            this.selectMinute = this.currentMinute;
        }
        this.setDate();
      }
      this.closePanel();
    },
    dayDisable(day) {
      if (typeof day == "number") {
        // 计算可选区间
        let dateNum =
          new Date(`${this.year}-${this.month}-${day}`).getTime() / 1000; //当前日历中的值对应秒
        let curDateNum =
          new Date(
            `${this.currentYear}-${this.currentMonth}-${this.currentDay}`
          ).getTime() / 1000; //当前时间对应秒
        let maxDayNum = curDateNum + this.maxRegularTime * 24 * 60 * 60; //当前时间加上选择范围对应秒
        if (dateNum >= curDateNum && dateNum <= maxDayNum) {
          return false;
        }
      }
      return true;
    },
    // 监视获取定时发布数据事件
    watchGetScheduleContent() {
      this.$bus.$on("getScheduleContent", () => {
        let dataObj = {
          scheduleDate: this.date,
          scheduleHour: this.selectHour,
          scheduleMinute: this.selectMinute,
        };
        this.$emit("send", dataObj);
      });
    },
  },
  computed: {
    // 计算日期数组
    daysArr() {
      // 计算所在月份1号为周几
      let day = new Date(`${this.year}-${this.month}`).getDay();
      let daysArr = new Array(day).fill(" ");
      let currentMonthDays = 0;
      if (this.month != 2) {
        switch (this.month) {
          case 1:
          case 3:
          case 5:
          case 7:
          case 8:
          case 10:
          case 12:
            currentMonthDays = 31;
            break;
          case 4:
          case 6:
          case 9:
          case 11:
            currentMonthDays = 30;
            break;
        }
      } else if (
        (this.year % 4 == 0 && this.year % 100 != 0) ||
        this.year % 400 == 0
      ) {
        currentMonthDays = 29;
      } else {
        currentMonthDays = 28;
      }
      for (let i = 1; i <= currentMonthDays; i++) {
        daysArr.push(i);
      }
      return daysArr;
    },
  },
  watch: {
    // date(newValue, oldValue) {
    //   console.log(newValue)
    // },
  },
};
</script>

<style lang="scss">
* {
  list-style: none;
  padding: 0;
  margin: 0;
}
.transition_box {
  display: flex;
  height: 54px;
  .schedule_bar {
    height: 42px;
    background-color: #f5f7fa;
    display: flex;
    flex: 1;
    align-items: center;
    border-radius: 4px;
    margin-top: 12px;
    .L_label {
      display: inline-block;
      color: #6d757a;
      font-size: 13px;
      padding: 0 6px 0 12px;
      font-family: "Microsoft Yahei", "WenQuanYi Micro Hei", Helvetica, Arial,
        sans-serif;
    }
    .date_picker {
      display: inline-flex;
      font-family: "Microsoft Yahei", "WenQuanYi Micro Hei", "Helvetica Neue",
        Helvetica, Arial, sans-serif;
      .date_input {
        width: 115px;
        height: 30px;
        line-height: 28px;
        font-size: 13px;
        color: #333;
        position: relative;
        box-sizing: border-box;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        outline: none;
        padding: 0;
        background-color: #fff;
        transition: all 0.2s;
        input {
          font-size: 12px;
          box-sizing: border-box;
          padding: 0 36px 0 12px;
          outline: none;
          width: 115px;
          height: 30px;
          color: #6d757a;
          border: 1px solid #e5e9f0;
          border-radius: 4px;
          &.active {
            border: 1px solid #00a1d6;
          }
        }
        .calendar {
          position: absolute;
          right: 10px;
          top: 9px;
          display: block;
          width: 12px;
          height: 12px;
          background-image: url("/static/video/rili.png");
          background-repeat: no-repeat;
          background-size: cover;
          background-position: center center;
          cursor: pointer;
          &.active {
            background-image: url("/static/video/rili_active.png");
          }
        }
        .date_panel {
          position: absolute;
          left: 0;
          top: 35px;
          z-index: 8;
          box-sizing: content-box;
          width: 247px;
          height: 220px;
          border: 1px solid #e5e9f0;
          border-radius: 4px;
          background-color: #fff;
          font-size: 13px;
          cursor: default;
          .ym {
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e9f0;
            line-height: 30px;
            font-weight: 600;
            color: #777;
            padding: 0 24px;
            & > * {
              display: inline-block;
            }
            .button {
              border: none;
              background-color: none;
              padding: 5px 8px;
              cursor: pointer;
              line-height: 16px;
              outline: none;
              .arrow {
                display: inline-block;
                height: 8px;
                width: 8px;
                margin-bottom: 1px;
                border-radius: 2px;
                border-top: 2px solid #777;
              }
              .left {
                border-left: 2px solid #777;
                transform: rotateZ(-45deg);
              }
              .right {
                border-right: 2px solid #777;
                transform: rotateZ(45deg);
              }
            }
          }
          .md {
            padding: 6px 12px;
            .week {
              display: flex;
              color: #555;
              font-weight: 600;
              & > span {
                width: 25px;
                margin-right: 4px;
                text-align: center;
                & + span {
                  margin-left: 4px;
                }
              }
            }
            .days {
              display: flex;
              align-items: center;
              flex-wrap: wrap;
              font-size: 12px;
              .day {
                display: inline-block;
                width: 25px;
                height: 25px;
                line-height: 25px;
                margin-right: 4px;
                margin-left: 4px;
                text-align: center;
                cursor: pointer;
                box-sizing: border-box;
                &:nth-child(7n + 1) {
                  margin-left: 0;
                }
                &:nth-child(7n) {
                  margin-right: 0;
                }
                &.disable {
                  cursor: not-allowed;
                  color: #ccc;
                }
                &.active {
                  border: 1px solid #00a1d6;
                  border-radius: 4px;
                  color: #00a1d6;
                  font-weight: 600;
                }
              }
            }
          }
        }
      }
      .scroll_input {
        position: relative;
        display: inline-flex;
        align-items: center;
        font-size: 12px;
        .s_input_wrap {
          .s_input {
            box-sizing: border-box;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            outline: none;
            background-color: #fff;
            height: 30px;
            width: 50px;
            margin-left: 12px;
            padding: 0 24px 0 6px;
            text-align: center;
            line-height: 28px;
            font-size: 12px;
            color: #6d757a;
            border: 1px solid #e5e9f0;
            border-radius: 4px;
            cursor: pointer;
            position: relative;
            transition: 0.2s;
            &.active {
              border: 1px solid #00a1d6;
            }
          }
        }
        .arrow_down {
          position: absolute;
          display: inline-block;
          left: 45px;
          height: 5px;
          width: 5px;
          border-radius: 2px;
          transition: 0.2s;
          pointer-events: none;
          box-sizing: content-box;
          border-bottom: 2px solid #777;
          border-left: 2px solid #777;
          transform: rotateZ(-45deg);
          &.active {
            transform: rotateZ(135deg);
            top: 12px;
            border-bottom: 2px solid #00a1d6;
            border-left: 2px solid #00a1d6;
          }
        }
        .s_label {
          margin-left: 6px;
          color: #6d757a;
        }
        .s_panel {
          z-index: 8;
          position: absolute;
          top: 35px;
          left: 12px;
          width: 48px;
          height: 150px;
          border: 1px solid #e5e9f0;
          background-color: #fff;
          font-size: 12px;
          cursor: default;
          overflow-y: scroll;
          &::-webkit-scrollbar {
            width: 5px;
            height: 8px;
            background-color: rgba(1, 1, 1, 0);
          }
          &::-webkit-scrollbar-thumb {
            background-color: #aaa;
            border-radius: 4px;
          }
          .s_item {
            height: 30px;
            box-sizing: border-box;
            text-align: center;
            line-height: 30px;
            cursor: pointer;
            color: #6d757a;
            &.active {
              color: #00a1d6;
            }
            &:hover {
              color: #00a1d6;
            }
          }
        }
      }
    }
  }
}
</style>